<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yang-da-xiong.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="前言BFS,DFS是数据结构与算法系列课程中非常重要，也是非常经典的两个算法。这一次，我想通过一道例题进行一次系统的总结，首先能够充分的理解BFS,DFS两个算法，然后可以掌握BFS,DFS两种算法思想，运用更加复杂，更加晦涩的算法题目中。">
<meta property="og:type" content="article">
<meta property="og:title" content="算法练习题7---BFS与DFS练习">
<meta property="og:url" content="https://yang-da-xiong.gitee.io/2022/01/17/%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0%E9%A2%987---BFS%E4%B8%8EDFS%E7%BB%83%E4%B9%A0/index.html">
<meta property="og:site_name" content="杨大熊的代码世界">
<meta property="og:description" content="前言BFS,DFS是数据结构与算法系列课程中非常重要，也是非常经典的两个算法。这一次，我想通过一道例题进行一次系统的总结，首先能够充分的理解BFS,DFS两个算法，然后可以掌握BFS,DFS两种算法思想，运用更加复杂，更加晦涩的算法题目中。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-01-17T13:30:03.582Z">
<meta property="article:modified_time" content="2022-03-01T06:14:06.540Z">
<meta property="article:author" content="杨大熊">
<meta property="article:tag" content="c++">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://yang-da-xiong.gitee.io/2022/01/17/%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0%E9%A2%987---BFS%E4%B8%8EDFS%E7%BB%83%E4%B9%A0/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>算法练习题7---BFS与DFS练习 | 杨大熊的代码世界</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">杨大熊的代码世界</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://yang-da-xiong.gitee.io/2022/01/17/%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0%E9%A2%987---BFS%E4%B8%8EDFS%E7%BB%83%E4%B9%A0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="杨大熊">
      <meta itemprop="description" content="各类IT知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="杨大熊的代码世界">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          算法练习题7---BFS与DFS练习
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-01-17 21:30:03" itemprop="dateCreated datePublished" datetime="2022-01-17T21:30:03+08:00">2022-01-17</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-03-01 14:14:06" itemprop="dateModified" datetime="2022-03-01T14:14:06+08:00">2022-03-01</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>BFS,DFS是数据结构与算法系列课程中非常重要，也是非常经典的两个算法。这一次，我想通过一道例题进行一次系统的总结，首先能够充分的理解BFS,DFS两个算法，然后可以掌握BFS,DFS两种算法思想，运用更加复杂，更加晦涩的算法题目中。</p>
<span id="more"></span>

<h1 id="一、题目描述"><a href="#一、题目描述" class="headerlink" title="一、题目描述"></a>一、题目描述</h1><p>题目“Red and Black”</p>
<p>有一个长方形的房间，铺着方形瓷砖，瓷砖为红色或黑色。一个人站在黑色砖上。他可以按上，下、左、右方向移动到相邻的瓷砖。但他不能在红色瓷砖上移动，只能在黑色瓷砖上移动。编程计算他可以到达的黑色瓷砖的数量。 </p>
<p>输入：第1行包含两个正整数 W 和 H . W 和 H 分别表示x方向和 y 方向上的瓷砖数量。 W 和 H 均不超过20。下面有 H 行，每行包含 W 个字符。每个字符表示一片瓷砖的颜色。用符号表示如下：“.” 表示黑色瓷砖；“#” 表示红色瓷砖；“@” 代表黑色瓷砖上的人，在数据集中只出现一次。</p>
<p> 输出：一个数字，这个人从初始瓷砖能到达的黑色瓷砖总数量（包括起点）。</p>
<p>样例输入：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">6 9</span><br><span class="line">....#.</span><br><span class="line">.....#</span><br><span class="line">......</span><br><span class="line">......</span><br><span class="line">......</span><br><span class="line">......</span><br><span class="line">......</span><br><span class="line">#@...#</span><br><span class="line">.#..#.</span><br><span class="line">11 9</span><br><span class="line">.#.........</span><br><span class="line">.#.#######.</span><br><span class="line">.#.#.....#.</span><br><span class="line">.#.#.###.#.</span><br><span class="line">.#.#..@#.#.</span><br><span class="line">.#.#####.#.</span><br><span class="line">.#.......#.</span><br><span class="line">.#########.</span><br><span class="line">...........</span><br><span class="line">11 6</span><br><span class="line">..#..#..#..</span><br><span class="line">..#..#..#..</span><br><span class="line">..#..#..###</span><br><span class="line">..#..#..#@.</span><br><span class="line">..#..#..#..</span><br><span class="line">..#..#..#..</span><br><span class="line">7 7</span><br><span class="line">..#.#..</span><br><span class="line">..#.#..</span><br><span class="line">###.###</span><br><span class="line">...@...</span><br><span class="line">###.###</span><br><span class="line">..#.#..</span><br><span class="line">..#.#..</span><br><span class="line">0 0</span><br></pre></td></tr></table></figure>



<p>样例输出：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">45</span><br><span class="line">59</span><br><span class="line">6</span><br><span class="line">13</span><br></pre></td></tr></table></figure>



<h1 id="二、BFS"><a href="#二、BFS" class="headerlink" title="二、BFS"></a>二、BFS</h1><p>BFS又称广度优先算法，所谓广度优先，是利用队列先进先出的特性，将每一个点可以到达的所有点都加入到队列中，然后移除该点，再遍历队列的首个元素，重复次操作。一般的题目中，都用二维数组来表示一个矩阵，一般可以移动的方向为上、下、左、右，那么需要对每一个队列中的点依次进行上、下、左、右这几个方向的查找，把符合要求的点放入队列中（该点一定是未被遍历过的）。直到队列中为空。</p>
<h1 id="三、DFS"><a href="#三、DFS" class="headerlink" title="三、DFS"></a>三、DFS</h1><p>DFS又称深度优先算法，所谓深度优先，是利用递归思想的特性，一直朝着一个方向遍历，直到没有办法前进为止，这个时候，当遇到无路可走时，就要进行回溯。那么如何实现回溯呢，这个其实我们不需要去考虑内部的实现过程，因为递归的回溯是依靠栈去实现，我们只需要记住递归函数的返回位置是它在所的函数中的位置的下一条语句。掌握好递归的这个特性，我们就可以去巧妙的设计递归程序，来解决该问题。</p>
<p>另一问题就是，如何在递归函数中进行其他方向的遍历？在该题目中，递归程序可以嵌套在for循环中，用for循环保证4个方向的执行，而递归算法本身又能保证优先朝着一个固定的方向一直遍历下去，那么二者结合也就构成了最终的DFS算法。</p>
<h1 id="四、程序代码—-BFS算法"><a href="#四、程序代码—-BFS算法" class="headerlink" title="四、程序代码—-BFS算法"></a>四、程序代码—-BFS算法</h1><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;bits/stdc++.h&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">char</span> room[<span class="number">23</span>][<span class="number">23</span>];  <span class="comment">//记录已经遍历过的节点，防止重复 </span></span><br><span class="line"><span class="keyword">int</span> dir[<span class="number">4</span>][<span class="number">2</span>]=&#123;&#123;<span class="number">-1</span>,<span class="number">0</span>&#125;,&#123;<span class="number">0</span>,<span class="number">-1</span>&#125;,&#123;<span class="number">1</span>,<span class="number">0</span>&#125;,&#123;<span class="number">0</span>,<span class="number">1</span>&#125;&#125;;  <span class="comment">//依次为向左，向上，向右，向下 </span></span><br><span class="line"><span class="keyword">int</span> Wx,Hy,num; </span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> CHECK(x,y)(x<span class="meta-string">&lt;Wx&amp;&amp;x&gt;</span>=0&amp;&amp;y&gt;=0&amp;&amp;y&lt;Hy)</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">node</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">int</span> x;</span><br><span class="line"><span class="keyword">int</span> y;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">BFS</span><span class="params">(<span class="keyword">int</span> dx,<span class="keyword">int</span> dy)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">queue</span>&lt;node&gt; q;  <span class="comment">//声明一个队列q,BFS算法的核心 </span></span><br><span class="line">	num=<span class="number">1</span>;</span><br><span class="line">	node start,next;  <span class="comment">//开始节点和下一个节点</span></span><br><span class="line">	start.x=dx;</span><br><span class="line">	start.y=dy;</span><br><span class="line">	q.push(start);</span><br><span class="line">	<span class="keyword">while</span>(!q.empty())</span><br><span class="line">	&#123;</span><br><span class="line">		start=q.front();</span><br><span class="line">		q.pop();</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">4</span>;i++)</span><br><span class="line">		&#123;</span><br><span class="line">			next.x=start.x+dir[i][<span class="number">0</span>];</span><br><span class="line">			next.y=start.y+dir[i][<span class="number">1</span>];</span><br><span class="line">			<span class="keyword">if</span>(CHECK(next.x,next.y)&amp;&amp;room[next.x][next.y]==<span class="string">&#x27;.&#x27;</span>)</span><br><span class="line">			&#123;</span><br><span class="line">				room[next.x][next.y]=<span class="string">&#x27;#&#x27;</span>; <span class="comment">//进队之后标记被处理 </span></span><br><span class="line">				num++;</span><br><span class="line">				q.push(next); </span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125; </span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> x,y,dx,dy;</span><br><span class="line">	<span class="keyword">while</span>(<span class="built_in">cin</span>&gt;&gt;Wx&gt;&gt;Hy)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span>(Wx==<span class="number">0</span>&amp;&amp;Hy==<span class="number">0</span>)  <span class="comment">//遇到0,0结束 </span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span>(y=<span class="number">0</span>;y&lt;Hy;y++)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">for</span>(x=<span class="number">0</span>;x&lt;Wx;x++)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="built_in">cin</span>&gt;&gt;room[x][y];</span><br><span class="line">				<span class="keyword">if</span>(room[x][y]==<span class="string">&#x27;@&#x27;</span>)</span><br><span class="line">				&#123;</span><br><span class="line">					dx=x;</span><br><span class="line">					dy=y;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		num=<span class="number">0</span>;</span><br><span class="line">		BFS(dx,dy);</span><br><span class="line">		<span class="built_in">cout</span>&lt;&lt;num&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>



<h1 id="五、程序代码—-DFS算法"><a href="#五、程序代码—-DFS算法" class="headerlink" title="五、程序代码—-DFS算法"></a>五、程序代码—-DFS算法</h1><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;bits/stdc++.h&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">char</span> room[<span class="number">23</span>][<span class="number">23</span>];  <span class="comment">//记录已经遍历过的节点，防止重复 </span></span><br><span class="line"><span class="keyword">int</span> dir[<span class="number">4</span>][<span class="number">2</span>]=&#123;&#123;<span class="number">-1</span>,<span class="number">0</span>&#125;,&#123;<span class="number">0</span>,<span class="number">-1</span>&#125;,&#123;<span class="number">1</span>,<span class="number">0</span>&#125;,&#123;<span class="number">0</span>,<span class="number">1</span>&#125;&#125;;  <span class="comment">//依次为向左，向上，向右，向下 </span></span><br><span class="line"><span class="keyword">int</span> Wx,Hy,num; </span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> CHECK(x,y)(x<span class="meta-string">&lt;Wx&amp;&amp;x&gt;</span>=0&amp;&amp;y&gt;=0&amp;&amp;y&lt;Hy)</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">node</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">int</span> x;</span><br><span class="line"><span class="keyword">int</span> y;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">DFS</span><span class="params">(<span class="keyword">int</span> dx,<span class="keyword">int</span> dy)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	num++;</span><br><span class="line">	room[dx][dy]=<span class="string">&#x27;#&#x27;</span>; <span class="comment">//初次遍历，及时标记</span></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">4</span>;i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">int</span> newx=dx+dir[i][<span class="number">0</span>];</span><br><span class="line">		<span class="keyword">int</span> newy=dy+dir[i][<span class="number">1</span>];</span><br><span class="line">		<span class="keyword">if</span>(CHECK(newx,newy)&amp;&amp;room[newx][newy]==<span class="string">&#x27;.&#x27;</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			DFS(newx,newy); </span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> x,y,dx,dy;</span><br><span class="line">	<span class="keyword">while</span>(<span class="built_in">cin</span>&gt;&gt;Wx&gt;&gt;Hy)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span>(Wx==<span class="number">0</span>&amp;&amp;Hy==<span class="number">0</span>)  <span class="comment">//遇到0,0结束 </span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span>(y=<span class="number">0</span>;y&lt;Hy;y++)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">for</span>(x=<span class="number">0</span>;x&lt;Wx;x++)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="built_in">cin</span>&gt;&gt;room[x][y];</span><br><span class="line">				<span class="keyword">if</span>(room[x][y]==<span class="string">&#x27;@&#x27;</span>)</span><br><span class="line">				&#123;</span><br><span class="line">					dx=x;</span><br><span class="line">					dy=y;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		num=<span class="number">0</span>;</span><br><span class="line">		DFS(dx,dy); </span><br><span class="line">		<span class="built_in">cout</span>&lt;&lt;num&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>杨大熊
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://yang-da-xiong.gitee.io/2022/01/17/%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0%E9%A2%987---BFS%E4%B8%8EDFS%E7%BB%83%E4%B9%A0/" title="算法练习题7---BFS与DFS练习">https://yang-da-xiong.gitee.io/2022/01/17/算法练习题7---BFS与DFS练习/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/c/" rel="tag"># c++</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/01/16/%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0%E9%A2%986---%E8%93%9D%E6%A1%A5%E6%9D%AF2017%E7%9C%81%E8%B5%9B%E2%80%9C%E6%89%BF%E5%8E%8B%E8%AE%A1%E7%AE%97%E2%80%9D/" rel="prev" title="算法练习题6---蓝桥杯2017省赛“承压计算”">
      <i class="fa fa-chevron-left"></i> 算法练习题6---蓝桥杯2017省赛“承压计算”
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/01/17/%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0%E9%A2%988---%E8%93%9D%E6%A1%A5%E6%9D%AF2017%E7%9C%81%E8%B5%9B%E2%80%9C%E6%96%B9%E6%A0%BC%E5%88%86%E5%89%B2%E2%80%9D/" rel="next" title="算法练习题8---蓝桥杯2017省赛“方格分割”">
      算法练习题8---蓝桥杯2017省赛“方格分割” <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E9%A2%98%E7%9B%AE%E6%8F%8F%E8%BF%B0"><span class="nav-number">2.</span> <span class="nav-text">一、题目描述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81BFS"><span class="nav-number">3.</span> <span class="nav-text">二、BFS</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81DFS"><span class="nav-number">4.</span> <span class="nav-text">三、DFS</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E7%A8%8B%E5%BA%8F%E4%BB%A3%E7%A0%81%E2%80%94-BFS%E7%AE%97%E6%B3%95"><span class="nav-number">5.</span> <span class="nav-text">四、程序代码—-BFS算法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E7%A8%8B%E5%BA%8F%E4%BB%A3%E7%A0%81%E2%80%94-DFS%E7%AE%97%E6%B3%95"><span class="nav-number">6.</span> <span class="nav-text">五、程序代码—-DFS算法</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="杨大熊"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">杨大熊</p>
  <div class="site-description" itemprop="description">各类IT知识分享</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">58</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/Yang-Da-xiong?tab=repositories" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Yang-Da-xiong?tab&#x3D;repositories" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/weixin_45775703?spm=1000.2115.3001.5343" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;weixin_45775703?spm&#x3D;1000.2115.3001.5343" rel="noopener" target="_blank"><i class="fab fa-codiepie fa-fw"></i>CSDN</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨大熊</span>
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>

<div class="theme-info">
<div class="powered-by"></div>
<span class="post-count">博客全站共56.5k字</span>
</div>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false});</script></body>
</html>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/schemes/clicklove.js"></script>
